package tech.heptagram.staff.cas.common;

import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import tech.heptagram.staff.cas.config.cas.domain.AuthorityInfo;
import tech.heptagram.staff.cas.config.cas.domain.UserInfo;
import tech.heptagram.staff.cas.domain.StaffEntity;
import tech.heptagram.staff.cas.domain.po.Menu;

/**
 * 员工信息获取工具类
 *
 * Created by yang on 2017/5/15.
 */
@Slf4j
public final class CurrentUserUtil {

    /**
     * 获取登录用户信息
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public static StaffEntity getCurrentUser() {
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        StaffEntity staff = new StaffEntity();
        BeanUtils.copyProperties(userInfo, staff);
        return staff;
    }

    public static List<Menu> getCurrentUserOperates() {
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        List<Menu> result = new ArrayList<>();
        for (GrantedAuthority grantedAuthority : userInfo.getAuthorities()) {
            AuthorityInfo authorityInfo = (AuthorityInfo) grantedAuthority;
            if (!authorityInfo.getType().equals(AuthorityInfo.OPERATE)) {
                continue;
            }
            Menu menu = new Menu();
            menu.setId(Integer.valueOf(authorityInfo.getAuthority()));
            menu.setName(authorityInfo.getName());
            menu.setPath(authorityInfo.getText());
            menu.setParentId(authorityInfo.getMenuId());
            result.add(menu);
        }
        return result;
    }

    public static List<Menu> getCurrentUserOperates(Integer menuId) {
        if(Objects.isNull(menuId)) {
            return new ArrayList<>();
        }

        List<Menu> lstOperates = getCurrentUserOperates();
        return lstOperates.stream()
            .filter(o->o.getParentId().intValue() == menuId)
            .collect(Collectors.toList());
    }
}
